var http = require('http');
var md5 = require('md5');
module.exports = function(RED) {
	function baiduTranslator(config) {
		RED.nodes.createNode(this, config);
		this.method = config.method || "GET";
		this.from = config.from || "en";
		this.to = config.to || "zh";
		this.url = config.url || "http://api.fanyi.baidu.com/api/trans/vip/translate";
		this.appid = config.appid;
		this.key = config.key;


		var node = this;

		this.on('input', function(msg) {
			var translator = msg.translator;
			var translatorOut = {
				message: translator.message || "",
				method: translator.method || node.method,
				from: translator.from || node.from,
				to: translator.to || node.to,
				url: translator.url || node.url,
				appid: translator.appid || node.appid,
				key: translator.key || node.key,
			};

			(function(method) {
				switch (true) {
					case /get/i.test(method):
						console.log('get method');

						var q = translatorOut.message.replace(/_/g," ");
						var srcLanguage = translatorOut.from;
						var desLanguage = translatorOut.to;
						var appid = translatorOut.appid;
						var key = translatorOut.key;
						var url = encodeURI(translatorOut.url);
						var salt = new Date().getTime();
						var sign = md5(appid + q + salt + key);
						var request = url + '?q=' + q + '&from=' + srcLanguage + '&to=' + desLanguage + '&appid=' + appid + '&salt=' + salt + '&sign=' + sign;
							request = encodeURI(request);
						console.log(request);
						http.get(request, function(res) {
							res.setEncoding('utf8');
								res.on('data', function(chunk) {
									
									// var test1=JSON.stringify(chunk);
									// console.log(test1);
									// console.log(JSON.parse(test1));
								
							
							msg.trans_result=JSON.parse(chunk);
							node.send(msg);
								});
							console.log(res.statusCode);

						})
						break;
					case /post/i.test(method):
						console.log('post method');
						break;
					default:
						console.log('method missing');
				}

			}(translatorOut.method));
			
			



		});
	}

	RED.nodes.registerType("baidu-translator", baiduTranslator);
}